<template>
  <div>
    <!--   头部搜索-->
    <el-card class="box-card" style="height: 70px">
      <el-form :inline="true" :model="searchForm" ref="searchForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="药品名称" prop="productName">
          <el-input v-model="searchForm.productName" placeholder="请输入药品名称" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="药品类型" prop="medicineType">
          <el-select v-model="searchForm.medicineType" placeholder="选择药品类型" autocomplete="off">
            <el-option
              v-for=" a in drugListTo"
              :value="a.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
          <el-button @click="resetForm('searchForm')">重置</el-button>
          <el-button type="success" @click="openAddFormVisible">添加</el-button>
          <el-button type="danger" @click="delBatch">批量删除</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!--      添加药品时弹出的表格-->
    <el-dialog :title="title"  width="50%" :visible.sync="drugAddFormVisible" :close-on-click-modal="false">
      <el-form :model="drug"  label-width="80px" :inline="true">
        <el-form-item label="药品名称" >
          <el-input v-model="drug.productName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="药品类型">
          <el-select v-model="drug.medicineType" placeholder="药品类型">
            <el-option
              v-for=" a in drugListTo"
              :value="a.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生产厂家">
          <el-input v-model="drug.manufacturer" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="规格">
          <el-select v-model="drug.specification" placeholder="请选择规格">
            <el-option label="10g/袋" value="10g/袋"></el-option>
            <el-option label="0.25g/粒" value="0.25g/粒"></el-option>
            <el-option label="5g/袋" value="5g/袋"></el-option>
            <el-option label="0.5g/袋" value="0.5g/袋"></el-option>
            <el-option label="0.25g/片" value="0.25g/片"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="药品单位">
          <el-select v-model="drug.medicineUnit" placeholder="药品单位">
            <el-option label="袋" value="袋"></el-option>
            <el-option label="粒" value="粒"></el-option>
            <el-option label="片" value="片"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="药品单价">
          <el-input-number v-model="drug.price" :precision="2" :step="0.1" :max="10"></el-input-number>
        </el-form-item>
        <div v-show="this.title === '增加商品信息'">
          <el-form-item label="生产日期">
            <el-date-picker type="date" placeholder="选择日期" value-format="yyyy-MM-dd HH:mm:ss" v-model="drug.shelfLife"
                            style="width: 100%;"></el-date-picker>
          </el-form-item>

          <el-form-item label="截至日期">
            <el-date-picker type="date" placeholder="选择日期" value-format="yyyy-MM-dd HH:mm:ss" v-model="drug.upToTime"
                            style="width: 100%;"></el-date-picker>
          </el-form-item>
        </div>
        <el-form-item label="库存数量">
          <el-input-number v-model="drug.inventory" @change="handleChange" :min="1" :max="500" label="描述文字"></el-input-number>
        </el-form-item>
<!--          -->
<!--        <el-form-item label="商品图">-->
<!--          <el-input v-model="drug.TradeChart" autocomplete="off"></el-input>-->
<!--        </el-form-item>-->

        <el-form-item prop="tradeCharts" label="上传商品图片" v-model="drug.tradeChart">
          <!--
          :http-request="uploadFile"  是用来覆盖默认的action的请求路径的
          action=""不能删除,因为是<el-upload>组件必填参数,不填会报错
          -->
          <el-upload
            class="upload-demo"
            drag
            action=""
            :http-request="uploadFile"
            :on-change="handleChange"
            multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
          <div>
            <!-- 上传后展现图片的地方 -->
            <img :src="fileSrc" width="200px">
          </div>
        </el-form-item>
        <el-form-item label="药品描述">
          <el-input type="textarea" v-model="drug.drugDescription"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addrug ">确 定</el-button>
      </div>
    </el-dialog>

<!--   列表展示-->
    <el-card class="box-card">
      <el-table
        :data="drugList"
        style="width: 100%;"
        @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          prop="productName"
          label="药品名称">
        </el-table-column>
        <el-table-column
          prop="medicineType"
          label="药品类型">
        </el-table-column>
        <el-table-column
          prop="manufacturer"
          label="生产厂家">
        </el-table-column>
        <el-table-column
          prop="specification"
          label="规格">
        </el-table-column>
        <el-table-column
          prop="medicineUnit"
          label="药品单位">
        </el-table-column>
        <el-table-column
          prop="price"
          label="药品单价">
        </el-table-column>
        <el-table-column
          prop="stockInTime"
          label="入库时间">
        </el-table-column>
        <el-table-column
          prop="updateTime"
          label="更新时间">
        </el-table-column>
        <el-table-column
          prop="shelfLife"
          label="生产日期">
        </el-table-column>
        <el-table-column
          prop="upToTime"
          label="截至日期">
        </el-table-column>
        <el-table-column
          prop="tradeChart"
          label="商品图">
         <template slot-scope="scope">
           <el-image
             style="width: 100px;height: 100px"
             :src="scope.row.tradeChart"
             fit="fill"></el-image>
         </template>
        </el-table-column>
        <el-table-column
          prop="inventory"
          label="库存数量">
        </el-table-column>
        <el-table-column
          prop="drugDescription"
          label="药品描述">
        </el-table-column>
<!--        <el-table-column-->
<!--          prop="sex"-->
<!--          label="性别">-->
<!--          <template slot-scope="scope">-->
<!--            <el-tag-->
<!--              :type="scope.row.sex == '1' ? 'primary' : 'success'"-->
<!--              disable-transitions>{{ scope.row.sex == '1' ? '男' : '女' }}-->
<!--            </el-tag>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column
          prop="controls"
          label="操作">
          <template slot-scope="scope">
            <el-button @click="handleEdit(scope.row)" type="text" size="small" >编辑</el-button>
            <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--
    page-size  每页最大展示条目
    current-page 默认第几页
    total 总条目数
    -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="PageNum"
        :page-sizes="[5, 6, 7, 8]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import {search,uploadPicture,addrug,handleDelete,delBatch,redact} from "@/api/drugProducts/drugList";
import {drugTypes} from "@/api/drugClassification/drugClassList";
import dayjs from "dayjs";


export default {
  name: "drugList",
  data() {
    return {
      title:"增加商品信息",
      drugList:[],
      multipleSelection:[],
      ids:[],
      drugListTo:[],
      searchForm: {
        productName: '',//药品名称
        medicineType: '',//药品类型
      },
      dialogFormVisible: false,
      pageSize: 5,
      total: 0,
      PageNum: 1,
      drugAddFormVisible:false,// 添加对话框,默认不可见
      drug:{
        productName:'',
        medicineType:'',
        manufacturer:'',
        specification:'',
        medicineUnit:'',
        price:0.0,
        shelfLife:'',
        upToTime:'',
        tradeChart:'',
        inventory:0,
        drugDescription:'',
      },
      file:null,
      fileSrc:null,
      fits: ['fill'],
      url:'',


    }
  },
  computed:{
  },
  methods: {
    //查询所有、模糊查询、分页
    search(){
      search(
        {
          productName:this.searchForm.productName,
          medicineType:this.searchForm.medicineType,
          PageNum:this.PageNum,
          pageSize:this.pageSize,
        }
      ).then((res)=>{
        console.log(res)
        if(res.code === 20000){
            this.drugList = res.data.list
        }
        this.total = res.data.total

        // //取出图片
        // for (let i=0; i< res.data.list.length; i++){
        //     this.url=res.data.list[i].tradeChar
        // }
      })
    },
    // 查所有树状结构,使用递归方法
    drugTypes(){
      drugTypes().then((res)=>{
        this.drugListTo = res.data;
        // console.log(res)
      })
    },
    //添加药品弹窗
    openAddFormVisible(){
      this.drug={};
      this.title="增加商品信息";
      this.drugAddFormVisible =true;

    },
    //编辑弹窗
    handleEdit(row){
      this.drug=row;
      // console.log(this.drug)
      this.title="编辑商品信息";
      this.drugAddFormVisible =true;
    },
    //编辑商品
    addrug(){
        if( this.title==="增加商品信息"){

          //日期格式化  生产日期
          this.drug.shelfLife = dayjs(this.drug.shelfLife ).format('YYYY-MM-DD HH:mm:ss')// 格式化成标准格式
          // 提交数据的其他操作
          this.drug.upToTime = dayjs(this.drug.upToTime ).format('YYYY-MM-DD HH:mm:ss')// 格式化成标准格式
          console.log(this.drug)
          console.log(this.drug.shelfLife)
          console.log(this.drug.upToTime)
          //添加商品
          addrug(this.drug).then((res)=>{
            if(res.code === 20000){
              this.$message.success("增加成功了！")
              this.search()
              this.drugAddFormVisible =false;
            }
          })
        }else if(this.title==="编辑商品信息"){
          //编辑商品信息
          redact(this.drug).then((res)=>{
              if(res.code === 20000){
                this.$message.success("修改成功!")
                this.search()
                this.drugAddFormVisible =false;
              }
          })
      }
    },

    onSubmit() {
      console.log('submit!');
    },
    //重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 列表序号
    handleSelectionChange(val) {
      this.multipleSelection = val;


      let ids = []
      ids = val.map(e =>e.productId)
      //付给外面的ids
      this.ids = ids;
      // console.log(ids.join(","))
      //   TODO 批量删除
      // console.log(this.ids)
    },
    //单删除
    handleDelete(row){
      // TODO 删除
      // console.log(row.productId);
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // console.log(row.measureId)
        handleDelete(row).then(() => {
          console.log("哈哈啊哈")
          this.PageNum = 1;
          this.search()
        }).catch((error) => {
          // this.$message.error('删除执行异常！' + error);
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      })
    },
    //批量删除
    delBatch(){
      // console.log(this.ids)
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delBatch(this.ids).then((res)=>{
          this.$message.success("删除成功!")
          this.PageNum = 1;
          this.search()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      })
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.search()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.PageNum = val;
      this.search()
    },
    //TODP:获得当前值
    handleChange(file){
      this.file = file.raw;
    },
    //前端连接后端获得到的图片路径
    uploadFile(){
      const file = this.file;
      // FormData是js对象,用于存储表单数据
      const formData = new FormData();
      formData.append("file", file); // 由后端接口决定,后端参数叫file

      uploadPicture(formData).then((res) => {
        console.log(res)
        this.$message({
          message: "上传成功",
          type: "success",
        });
        this.fileSrc = res.data
        this.drug.tradeChart = res.data
        console.log(this.drug.tradeChart)
        console.log("fileSrc",this.fileSrc)
      });
    },
  },
  created(){
    //查所有
   this.search()
    this.drugTypes()
  }

}
</script>

<style scoped lang="scss">

</style>
